<template>
  <div style="padding: 10px; width: 100%">
    <div>
      <p class="count">
        {{ this.form.gradeList.name }}{{ this.course.name
        }}{{ this.course.gradeList.courseList[0].name }}成绩
      </p>
    </div>

    <div style="float: left; width: 580px">
      <el-input
        placeholder="请输入学生学号"
        v-model="studentId"
        style="width: 200px"
      >
        <template #append>
          <el-button icon="el-icon-search" @click="load"></el-button>
        </template>
      </el-input>
      <el-upload
        :show-file-list="false"
        :before-upload="beforeUpload"
        :on-success="onSuccess"
        :on-error="onError"
        :disabled="importDataDisabled"
        action="/api/escore/upload"
        :data="{
          examId: this.form.id,
          gradeId: this.form.gradeId,
          clazzId: this.course.id,
          courseId: this.course.gradeList.courseList[0].id,
        }"
        style="display: inline-flex; margin-left: 20px"
      >
        <el-button
          size="small"
          type="success"
          :icon="importDataBtnIcon"
          :disabled="importDataDisabled"
        >
          {{ importDataBtnText }}</el-button
        >
      </el-upload>

      <el-button
        type="success"
        style="margin-left: 20px"
        icon="el-icon-download"
        @click="outExe"
        >导出数据</el-button
      >
      <el-button @click="DataEchart" type="info" style="margin-left: 20px"
        >数据分析</el-button
      >
    </div>
    <div style="margin: 10px 0; width: 250px; float: right; flex: 1">
      <span class="count">最高分:{{ this.heightscore }}</span>
      <span class="count">平均分:{{ this.avg }}</span>
    </div>
    <el-table :data="tableData" border stripe style="width: 99%" height="74vh">
      <el-table-column prop="stuId" label="学号" sortable />
      <el-table-column prop="name" label="姓名" />
      <el-table-column prop="score" label="成绩" sortable />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button
            @click="handleEdit(scope.row)"
            size="mini"
            type="primary"
            plain
            >修改</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
      :title="title"
      v-model="scoreVisible"
      width="50%"
      :before-close="dialogClose"
    >
      <el-form :model="scoreForm" ref="form" :rules="rules">
        <el-row>
          <el-col span="12">
            <el-form-item label="姓名" label-width="100px">
              <el-input
                v-model="scoreForm.name"
                placeholder="请输入学号"
                disabled="true"
              />
            </el-form-item>
          </el-col>
          <el-col span="12">
            <el-form-item label="成绩" label-width="100px">
              <el-input v-model="scoreForm.score" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="scoreVisible = false">取 消</el-button>
          <el-button type="primary" @click="update()">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <div style="margin: 10px 0">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import request from "../../utils/request";

export default {
  name: "List",
  data() {
    return {
      importDataBtnText: "导入成绩",
      importDataBtnIcon: "el-icon-upload",
      importDataDisabled: false,
      scoreVisible: false,
      //当前页
      currentPage: 1,
      pageSize: 10,
      total: 0,
      tableData: [],
      excelData:[],
      form: {},
      course: {},
      scoreForm: {},
      score: "",
      studentId: "",
      // 平均分
      avg: "",
      // 最高分
      heightscore: null,
    };
  },
  created() {
    let strexam = sessionStorage.getItem("examInfo") || "{}";
    this.form = JSON.parse(strexam);
    let strcourse = sessionStorage.getItem("courseInfo") || "{}";
    this.course = JSON.parse(strcourse);
    this.load();
    this.getAvg();
    this.getHeightScore();
  },
  methods: {
    DataEchart() {
      this.$router.push("/data");
    },
    // 分页查询
    load() {
      request
        .get("/escore/teacherscore", {
          params: {
            PageNum: this.currentPage,
            PageSize: this.pageSize,
            examId: this.form.id,
            gradeId: this.form.gradeId,
            clazzId: this.course.id,
            courseId: this.course.gradeList.courseList[0].id,
            studentId: this.studentId,
          },
        })
        .then((res) => {
          console.log("考试成绩");
          console.log(res);
          this.tableData = res.data.records;
          this.total = res.data.total;
          for (let i = 0; i < res.data.records.length; i++) {
            this.tableData[i].name = res.data.records[i].student.stuName;
            this.tableData[i].stuId = res.data.records[i].student.stuId;
          }
          console.log(this.tableData);
          this.getAvg();
          this.getHeightScore()
        });
    },
    // 打开编辑框
    handleEdit(row) {
      console.log(row);
      this.scoreForm = JSON.parse(JSON.stringify(row));
      this.scoreVisible = true;
    },
    // 修改学生成绩
    update() {
      console.log(this.scoreForm);
      request.put("/escore/update", this.scoreForm).then((res) => {
        console.log(res);
        if (res.code === "0") {
          this.$message({
            type: "success",
            message: "更新成功",
          });
          this.scoreVisible = false;
        } else {
          this.$message({
            type: "error",
            message: res.msg,
          });
        }
        this.load();
      });
    },
    // 计算平均分
    getAvg() {
      request
        .get("/escore/clazzavg", {
          params: {
            examId: this.form.id,
            gradeId: this.form.gradeId,
            clazzId: this.course.id,
            courseId: this.course.gradeList.courseList[0].id,
          },
        })
        .then((res) => {
          console.log("平均分");
          console.log(res);
          this.avg = res.data;
        });
    },
    // 最高分
    getHeightScore() {
      request
        .get("/escore/height/score", {
          params: {
            examId: this.form.id,
            gradeId: this.form.gradeId,
            clazzId: this.course.id,
            courseId: this.course.gradeList.courseList[0].id,
          },
        })
        .then((res) => {
          this.heightscore = res.data;
        });
    },
    // 上传文件前的钩子
    beforeUpload() {
      (this.importDataBtnText = "正在导入"),
        (this.importDataBtnIcon = "el-icon-loading");
      this.importDataDisabled = true;
    },
    // 上传成功钩子
    onSuccess(res) {
      (this.importDataBtnText = "导入成绩"),
        (this.importDataBtnIcon = "el-icon-upload");
      this.importDataDisabled = false;
       if (res.code ==="-1") {
        this.$message({type:"error",message:res.msg})
      }else{
        this.$message({type:"success",message:"上传成功"})
      }
      this.load();
    },
    // 上传失败钩子
    onError() {
      (this.importDataBtnText = "导入成绩"),
        (this.importDataBtnIcon = "el-icon-upload");
      this.importDataDisabled = false;
      this.$message({type:"error",message:"上传失败"})
      this.load();
    },
    // 导出excel表格
    outExe() {
      this.$confirm("此操作将导出excel文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.excelData = this.tableData; //你要导出的数据list。
          this.export2Excel();
        })
        .catch(() => {});
    },

    export2Excel() {
      var that = this;
      require.ensure([], () => {
        const { export_json_to_excel } = require("../../excal/Export2Excel"); //这里必须使用绝对路径，根据自己的命名和路径
        const tHeader = [
          "学号",
          "姓名",
          "成绩",
          
        ]; // 导出的表头名
        const filterVal = [
          "stuId",
          "name",
          "score",
        ]; // 导出的表头字段名
        const list = that.excelData;
        // that.excelData为传入的数据
        const data = that.formatJson(filterVal, list);
        export_json_to_excel(tHeader, data, this.course.name+this.course.gradeList.courseList[0].name+"成绩"); // 导出的表格名称，根据需要自己命名
        // tHeader为导出Excel表头名称，`xxxxxx`即为导出Excel名称
      });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) => filterVal.map((j) => v[j]));
    },
    //改变当前每页的个数触发
    handleSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.load();
    },
    //改变当前页码触发
    handleCurrentChange(pageNum) {
      this.currentPage = pageNum;
      this.load();
    },
  },
};
</script>
<style>
.count {
  color: #999;
  margin-top: 10px;
  margin-left: 20px;
  font-size: 15px;
  font-weight: bold;
  text-align: center;
}
</style>


